import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components"
import { useRef, useState } from "react"
import { FormInstance } from "antd/lib"
import useRpcApi from "@/hooks/useRpcApiHook"
import { Button, Popconfirm, message } from "antd"
import { PlusOutlined } from "@ant-design/icons"
import { RoleModel } from "@/components/model"
import RoleSettingsFormModal from "./RoleSettingsFormModal"
import RolePermisModal from "./RolePermisModal"

type PageItem = RoleModel;

function RoleSettings() {
    const actionRef = useRef<ActionType>()
    const formRef = useRef<FormInstance>()
    const { pageQuery, apiRpc } = useRpcApi()

    const queryTableData = (params: any): Promise<any> => {
        const { current, pageSize } = params
        const _params = { ...params }
        delete _params.current
        delete _params.pageSize
        return pageQuery("role.query.page", current, pageSize, _params)
    }

    // 定义表格列
    const columns: ProColumns<PageItem>[] = [
        {
            title: "角色编码",
            dataIndex: "role_code",
            key: "role_code",
            width: "15%",
            ellipsis: true,
            editable: false, // 是否可编辑
        },
        {
            title: "角色名称",
            dataIndex: "role_name",
            key: "role_name",
            width: "15%",
            ellipsis: true,
        },
        {
            title: "角色描述",
            dataIndex: "role_description",
            key: "role_description",
            width: "15%",
            ellipsis: true,
            search: false,
        },
        {
            title: "创建时间",
            dataIndex: "create_time",
            key: "create_time",
            width: "15%",
            ellipsis: true,
            search: false,
            editable: false,
        },
        {
            title: "更新时间",
            dataIndex: "update_time",
            key: "update_time",
            width: "15%",
            ellipsis: true,
            search: false,
            editable: false,
        },
        {
            title: "操作",
            valueType: "option",
            key: "option",
            width: "10%",
            render: (_text, record, _, action) => [
                <a
                    onClick={() => {
                        action?.startEditable?.(record.id)
                    }}
                >
                    编辑
                </a>,
                <a
                    onClick={() => {
                        setFormData(record)
                        setRolePermisModalShow(true)
                    }}
                >
                    权限
                </a>,
                <Popconfirm
                    title=""
                    description="删除此项?"
                    onConfirm={() => {
                        deleteRow(undefined, record)
                    }}
                    onCancel={() => {
                        console.log(record, "   act  ", action)
                    }}
                    cancelText="取消"
                    okText="确定"
                >
                    <a>删除</a>
                </Popconfirm>,

            ],
        },
    ]

    const [roleSettingsFormModalShow, setRoleSettingsFormModalShow] = useState(false)
    const [formData, setFormData] = useState<PageItem | undefined>(undefined)

    const [rolePermisModalShow, setRolePermisModalShow] = useState(false)

    function updateRow(rowKey: any, row: PageItem) {
        apiRpc("role.update", row)
            .then(
                () =>
                    // 刷新
                    actionRef?.current?.reload(),
            )
            .catch(err => {
                message.error(`${err.message}`)
                // 保持编辑状态
                actionRef?.current?.startEditable(rowKey)
            })
    }

    /**
     * 删除操作
     * @param _key
     * @param row
     */
    function deleteRow(_key: any | undefined, row: any) {
        // 删除的回调函数
        apiRpc("role.delete", row).catch(err => {
            message.error(`${err.message}`)
        })
        actionRef?.current?.reload()
    }

    return (
        <div>
            <RoleSettingsFormModal
                open={roleSettingsFormModalShow}
                formData={formData}
                handleCancel={() => setRoleSettingsFormModalShow(false)}
                handleOk={() => {
                    setRoleSettingsFormModalShow(false)
                    actionRef?.current?.reload()
                }}
            />
            <RolePermisModal open={rolePermisModalShow}
                role={{
                    id: formData?.id || 0
                    , role_code: formData?.role_code || ""
                    , role_name: formData?.role_name || ""
                    , role_description: formData?.role_description || ""
                    , create_time: formData?.create_time || ""
                    , update_time: formData?.update_time || ""
                }}
                handleCancel={() => setRolePermisModalShow(false)}
                handleOk={() => setRolePermisModalShow(false)}
            />
            <ProTable<PageItem>
                actionRef={actionRef}
                cardBordered
                formRef={formRef}
                rowKey={"id"}
                scroll={{
                    x: "max-content",
                    y: "calc(100vh - 400px)",
                }}
                bordered
                form={{}}
                columns={columns}
                size={"small"}
                request={params => queryTableData(params)}
                toolBarRender={() => [
                    <Button key="primary" type="primary" onClick={() => setRoleSettingsFormModalShow(true)}>
                        <PlusOutlined />
                        新建
                    </Button>,
                ]}
                // 添加 editable 配置来支持行内编辑
                editable={{
                    type: "multiple",
                    deleteText: "",
                    onSave: async (key, row) => {
                        // 保存编辑内容的回调函数
                        console.log("保存", row)
                        updateRow(key, row)
                    },
                    onCancel: async (_key) => {
                        // 取消编辑的回调函数
                        actionRef?.current?.reload()
                    },
                    onDelete: async (key, row) => {
                        deleteRow(key, row)
                    },
                }}
            ></ProTable>
        </div>
    )
}

export default RoleSettings
